// var app = chrome.runtime.getBackgroundPage();

function hello() {
  var ftext = getftext(); 
  var cookies = getCookies(ftext);
  setCookies(cookies);
  var url = getUrl(ftext,"POST",true);
  
  if(url)
  {
  	var body = getBody(ftext);

  	mySubmit(url,body);
  }
  else
  {
  	alert("暂时不支持get请求")
  	//window.open(getHeader("GET"));
  }
 
}


function getftext()
{
  // chrome.tabs.executeScript({
  //   file: 'alert.js'
  // }); 
  var ftext= document.getElementById('ftext').value;
  if(!ftext){
  	alert("请输入fiddler请求报文")
  }
  else
  {
  	localStorage['ftext'] = document.getElementById('ftext').value;
  }
  return ftext;
}

function getCookies(ftext)
{

  try
  {
  	  var cookieText = getHeader(ftext,'Cookie');
  	  var origin =  getHeader(ftext,'Origin'); 
	  var cookies = [];
	  var cookieStrs = cookieText.split(';');
	  
	  for(var j= 0;j < cookieStrs.length;j++)
	  {
	  	var cookieArray = cookieStrs[j].trim().split('='); 
	  	cookies.push({"name":cookieArray[0],"url":origin,"value": cookieArray[1]});
	  }
	  return cookies;
  }
  catch(err)
  {
  	alert("格式有误:" + err);
  }

}
function getHeader(ftext,key)
{
	var regex = new RegExp("[\\s\\S]"+key+":(.*)[\\s\\S]","i"); 
	return ftext.split(regex)[1];
}

function getUrl(ftext,isPost)
{
	var key = "POST";
	if(!isPost)
	{
		key="GET";
	}
	var regex = new RegExp(key+" (.*)HTTP\/1.1[\\s\\S]","i");
	return ftext.split(regex)[1];
}
function getBody(ftext)
{
	return ftext.split(/[\r\n]{2}(.*)/)[1];
}
var callback = function (cookie){

        console.log("error :" + JSON.stringify(cookie));
        console.log(chrome.extension.lastError);
        console.log(chrome.runtime.lastError);
};
function removeCookies(origin)
{
	chrome.cookies.set({"name":'initIndexSearchzh_cn',"url":origin,"value":'0'},callback);
	chrome.cookies.set({"name":'IntlVisitedHotelCookiezh_cn',"url":origin,"value":'0'},callback);
}
function setCookies(cookies)
{
	try
	{
		removeCookies(cookies[0].url);
		for(var i=0;i< cookies.length;i++)
		{
			chrome.cookies.set(cookies[i],callback);
		}
	}
	catch(err)
	{
		alert(err);
	}
	
}
function mySubmit(url,bodyStr)
{
	var form = document.getElementById('myForm');
	form.action = url;
	var paras = myTrim(bodyStr).split('&');
	
	for(var x =0; x < paras.length; x++)
	{ 
		var nv = paras[x].split('='); 
		form.appendChild(createField(nv[0],decodeURIComponent(nv[1])));
	} 
	form.submit();
}
function createField(name,value)
{
	var i = document.createElement("input");
	i.setAttribute('type',"hidden");
	i.setAttribute('name',name);
	i.setAttribute('value',value);
	return i;
}
function myTrim(x) {
    return x.replace(/^\s+|\s+$/gm,'');
}
document.getElementById('ftext').value = localStorage['ftext'];
document.getElementById('clickme').addEventListener('click', hello);